#include "CanSend.h"
#include "fdcan.h"

#include "string.h"
FDCAN_TxHeaderTypeDef TxHeader={0};

void canfd_Filterinit(FDCAN_HandleTypeDef *hfdcan)
{
	FDCAN_FilterTypeDef sFilter={0};
	sFilter.FilterConfig=FDCAN_FILTER_TO_RXFIFO0;
	sFilter.FilterID1=0x000;
	sFilter.FilterID2=0x7FF;
	sFilter.FilterIndex=0;
	sFilter.FilterType=FDCAN_FILTER_MASK;
	sFilter.IdType=FDCAN_STANDARD_ID; 

	if (HAL_FDCAN_ConfigFilter(hfdcan, &sFilter) != HAL_OK)
  {
    Error_Handler();
  }

  if (HAL_FDCAN_ActivateNotification(hfdcan, FDCAN_IT_RX_FIFO0_NEW_MESSAGE, 0) != HAL_OK)
  {
    Error_Handler();
  }
	if (HAL_FDCAN_Start(hfdcan) != HAL_OK)
  {
    Error_Handler();
  }

}

void CANFD_SendMsg(FDCAN_HandleTypeDef *hfdcan,uint16_t msgID,uint8_t *Data)
{
	TxHeader.BitRateSwitch=FDCAN_BRS_OFF; 
	TxHeader.DataLength=FDCAN_DLC_BYTES_8 ;
	TxHeader.ErrorStateIndicator=FDCAN_ESI_ACTIVE;
	TxHeader.FDFormat=FDCAN_CLASSIC_CAN;//CANFD
	TxHeader.Identifier=msgID;//CAN ID
	TxHeader.IdType=FDCAN_STANDARD_ID;
	TxHeader.MessageMarker=0;
	TxHeader.TxEventFifoControl=FDCAN_NO_TX_EVENTS;
	TxHeader.TxFrameType=FDCAN_DATA_FRAME;
	
	HAL_FDCAN_AddMessageToTxFifoQ(hfdcan,&TxHeader,Data);
}

static FDCAN_RxHeaderTypeDef RxHeader1;
static FDCAN_RxHeaderTypeDef RxHeader2;
static FDCAN_RxHeaderTypeDef RxHeader3;
uint8_t RxData1[8]={0};
uint8_t RxData2[8]={0};
uint8_t RxData3[8]={0};
void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs)
{
	if((RxFifo0ITs & FDCAN_IT_RX_FIFO0_NEW_MESSAGE) != RESET)
	{
	 if(hfdcan->Instance == FDCAN1)
		{
				if(HAL_FDCAN_GetRxMessage(&hfdcan1, FDCAN_RX_FIFO0, &RxHeader1, RxData1)==HAL_OK)
				{
					CANFD_SendMsg(&hfdcan1,RxHeader1.Identifier,RxData1);
					
				}
		}
		if(hfdcan->Instance == FDCAN2)
		{
				if(HAL_FDCAN_GetRxMessage(&hfdcan2, FDCAN_RX_FIFO0, &RxHeader2, RxData2)==HAL_OK)
				{
					CANFD_SendMsg(&hfdcan2,RxHeader2.Identifier,RxData2);
					
				}
		}
		if(hfdcan->Instance == FDCAN3)
		{
				if(HAL_FDCAN_GetRxMessage(&hfdcan3, FDCAN_RX_FIFO0, &RxHeader3, RxData3)==HAL_OK)
				{
					CANFD_SendMsg(&hfdcan3,RxHeader3.Identifier,RxData3);
					
				}
		}
	}
}